#!/bin/bash

# doar - mail aggregation script based on mpop and msmtp
# Written in 2014 by fr33domlover <fr33domlover@riseup.net>
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of the CC0 Public Domain Dedication along with
# this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

global_config_dir="/etc/doar"
user_config_dir=".config/doar"
mpop_config="mpoprc"
#msmtp_config="msmtprc"
account_defs="account_defs"
account_list="account_list"
temp_config=".generated_temp_config"

defs="${user_config_dir}/${account_defs}"
list="${user_config_dir}/${account_list}"
mpoprc="${global_config_dir}/${mpop_config}"
#msmtprc="${global_config_dir}/${msmtp_config}"
mpoprc_full="${user_config_dir}/${temp_config}"

users=`awk -F':' '{ if ( $3 >= 500 ) print $1 ":" $6 }' /etc/passwd`
for user in $users
do
	user_name="$(echo "$user" | sed s/^\\\([^:]\\+\\\):.*$/\\1/)"
	user_home="$(echo "$user" | sed s/^[^:]\\+://)"
	user_mpoprc="${user_home}/${defs}"
	user_list="${user_home}/${list}"
	final_mpoprc="${user_home}/${mpoprc_full}"
	if test -f "$user_mpoprc"  &&  test -f "$user_list"
	then
		accounts="$(sed /^#/d "$user_list" | tr "\n" " ")"
		export DOAR_USER="$user_name"
		cat "$mpoprc" "$user_mpoprc" > "$final_mpoprc"
		chmod 400 "$final_mpoprc"
		mpop --file="$final_mpoprc" -- $accounts
		rm "$final_mpoprc"
	fi
done
